package cn.xiaolang.thread.concurrent;

/**
 * 单生产单消费问题
 * @author fuhw/Dean
 * @date 2020-03-06
 */
public class ProduceConsumerOneToOne {

    /**
     * 结果：
     * 1、生产者或消费者会一直处于生产或消费状态
     * 2、商品重复生产，容器中已经没有商品，消费者还在从容器中获取商品
     */
    public static void main(String[] args) {
        // 生产者消费者共享的资源
        ShareResource resource = new ShareResource();
        new Thread(new Producer(resource), "P").start();
        new Thread(new Consumer(resource), "C").start();
    }


    /**
     * 生产者
     */
    static class Producer implements Runnable {

        private ShareResource resource;

        Producer(ShareResource resource) {
            super();
            this.resource = resource;
        }

        @Override
        public void run() {
            int num = 1;
            while (true) {
                resource.put("包子" + num);
                num++;
            }
        }
    }

    static class Consumer implements Runnable {
        private ShareResource resource;

        Consumer(ShareResource resource) {
            super();
            this.resource = resource;
        }

        @Override
        public void run() {
            while (true) {
                resource.gain();
            }
        }
    }
}

